﻿//-----------------------------------------------------------------------
// <copyright file="WebClientWithTimeout.cs" company="AFS">
// Copyright (c) AFS. All rights reserved.
//
//    This file is part of Chatbox.
//
//    Chatbox is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Lesser General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    Chatbox is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU Lesser General Public License for more details.
//
//    You should have received a copy of the GNU Lesser General Public License
//    along with Chatbox. If not, see http://www.gnu.org/copyleft/lesser.html
// </copyright>
//----------------------------------------------------------------------- 

namespace ChatBox.Engine
{
    using System;
    using System.Net;

    /// <summary>
    /// A Web Client with a timeout in Miliseconds
    /// Closely based on code from http://www.copypastecode.com/7658
    /// </summary>
    public class WebClientWithTimeout : WebClient
    {
        /// <summary>
        /// The default timout is 3 minutes (in miliseconds)
        /// </summary>
        private const int DefaultTimeout = 180000;

        /// <summary>
        /// Initializes a new instance of the WebClientWithTimeout class
        /// </summary>
        public WebClientWithTimeout()
        {
            this.Timeout = DefaultTimeout;
        }

        /// <summary>
        /// Gets or sets the time in milsecongs after which connections will fail
        /// </summary>
        public int Timeout { get; set; }
        
        /// <summary>
        /// Generate a web request. The timeout is applied
        /// </summary>
        /// <param name="address">the address to connect to</param>
        /// <returns>the web request</returns>
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);

            if (request.GetType() == typeof(HttpWebRequest))
            {
                request.Timeout = this.Timeout;
            }

            return request;
        }
    }
}
